import dynamic from 'next/dynamic';
import EditorSuspense from '@/app/[locale]/editor/load';
import type { TMetadata } from '@/types';
import {
  type ChangeEvent,
  type Dispatch,
  forwardRef,
  type SetStateAction,
} from 'react';
import { useTranslations } from 'use-intl';

const DynamicEditor: any = dynamic(() => import('./editor'), {
  loading: () => <EditorSuspense />,
  ssr: false,
});

export default forwardRef(function Editor(
  {
    id,
    initialData,
    metadata,
    extraData,
    type,
    name,
    setName,
    setIsSaving,
    showName,
  }: {
    id?: string | number;
    initialData?: string;
    metadata: TMetadata;
    extraData?: any;
    type: 'newPost' | 'editPost' | 'postTemplate' | 'message' | 'section';
    showName?: false;
    setIsSaving?: Dispatch<SetStateAction<boolean>>;
  } & (
    | {
        name: string;
        setName: (name: string) => void;
      }
    | {
        name?: never;
        setName?: never;
      }
  ),
  ref,
) {
  const t = useTranslations('PostEditPage');

  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setName!(value);
  }

  if (typeof name !== undefined && typeof setName === 'function') {
    return (
      <div className="row">
        <div className="col">
          <input
            type="text"
            name="name"
            value={name}
            className="form-control text-center mb-4"
            placeholder={t('titleRequired')}
            onChange={onChange}
          />

          <DynamicEditor
            id={id}
            initialData={initialData}
            metadata={metadata}
            extraData={extraData}
            type={type}
            currentEditorRef={ref}
            setIsSaving={setIsSaving}
          />
        </div>
      </div>
    );
  }

  return (
    <DynamicEditor
      id={id}
      initialData={initialData}
      metadata={metadata}
      extraData={extraData}
      type={type}
      currentEditorRef={ref}
    />
  );
});
